package com.zrx.zrxpicturebackend.aop;

import com.zrx.zrxpicturebackend.annotation.AuthCheck;
import com.zrx.zrxpicturebackend.exception.BusinessException;
import com.zrx.zrxpicturebackend.exception.ErrorCode;
import com.zrx.zrxpicturebackend.model.entity.User;
import com.zrx.zrxpicturebackend.model.enums.UserRoleEnum;
import com.zrx.zrxpicturebackend.service.UserService;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

@Aspect
@Component
public class AuthInterceptor {


    @Resource
    private UserService userService;

    /**
     * 执行拦截
     * @param joinPoint 切入点
     * @param authCheck 注解
     * @return
     */
    @Around("@annotation(authCheck)")
    public Object doIntercept(ProceedingJoinPoint joinPoint, AuthCheck authCheck) throws Throwable {

        String mustRole = authCheck.mustRole();
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest();
        // 获取当前登录用户
        User loginUser = userService.getLoginUser(request);
        UserRoleEnum userRoleEnum = UserRoleEnum.getEnumByValue(mustRole);
        //不需要权限 直接放行
        if (userRoleEnum == null){
            return joinPoint.proceed();
        }
        //以下都是有权限才通过
        //获取当前用户具有的权限
        String userRole = loginUser.getUserRole();
        //没有权限
        if (userRole == null){
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }

        //要求必须要有管理员权限
        if (UserRoleEnum.ADMIN.getValue().equals(mustRole) && !UserRoleEnum.ADMIN.getValue().equals(userRole)){
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }

        //放行
        return joinPoint.proceed();
    }
}
